package com.zzyl.nursing.service.impl;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.ServiceProperty;
import com.huaweicloud.sdk.iotda.v5.model.ShowProductRequest;
import com.huaweicloud.sdk.iotda.v5.model.ShowProductResponse;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.*;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.health.IdentifierVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

import static com.zzyl.common.constant.CacheConstants.IOT_DEVICE_LAST_DATA;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-26
 */
@Service
@Slf4j
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private IDeviceDataService deviceDataService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private IoTDAClient client;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    /**
     * 小程序端登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //获取openid  微信接口获取
        String openid = wechatService.getOpenid(dto.getCode());

        //根据openid查询用户信息
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openid));

        //如果用户为空，构建用户，赋值一个openid
        if(ObjectUtil.isEmpty(familyMember)){
            familyMember = FamilyMember
                    .builder()
                    .openId(openid)
                    .build();
        }

        //获取用户的手机号  微信接口获取
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //保存或更新用户
        insertOrUpdateFamilyMember(familyMember,phone);

        //生成token返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("userName", familyMember.getName());

        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(familyMember.getName());
        loginVo.setToken(token);

        return loginVo;
    }

    /**
     * 保存或更新用户
     *
     * @param familyMember
     * @param phone
     */
    private void insertOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //判断手机号与数据库的手机号是否一致
        if(ObjectUtil.notEqual(familyMember.getPhone(),phone)){
            familyMember.setPhone(phone);
        }
        //判断是否存在id，如果存在id，则更新，不存在则保存
        if(ObjectUtil.isNotEmpty(familyMember.getId())){
            updateById(familyMember);
            return;
        }
        //获取用户的昵称
        int index = (int)(Math.random() * DEFAULT_NICKNAME_PREFIX.size());
        String nickName = DEFAULT_NICKNAME_PREFIX.get(index) + StringUtils.substring(phone,7,11);
        familyMember.setName(nickName);
        //保存
        save(familyMember);

    }

    @Autowired
    private IElderService elderService;

    @Autowired
    private ICheckInService checkInService;

    @Autowired
    private IFamilyMemberElderService  familyMemberElderService;

    @Override
    public void add(FamilyMemberElderDto familyMemberElderDto) {
        String idCard = familyMemberElderDto.getIdCard();
        String name = familyMemberElderDto.getName();
        String remark = familyMemberElderDto.getRemark();
        if (StrUtil.isEmpty(idCard) || idCard == "") {
            throw new BaseException("老人身份证不能为空");
        }
        if (StrUtil.isEmpty(name) || name == "") {
            throw new BaseException("老人姓名不能为空");
        }
        if (StrUtil.isEmpty(remark) || remark == "") {
            throw new BaseException("对老人称呼不能为空");
        }
        //家人姓名和身份证号必须是养老院入住的老人
        CheckIn result = checkInService.lambdaQuery()
                .eq(CheckIn::getElderName, name)
                .eq(CheckIn::getIdCardNo, idCard)
                .one();

        if (ObjectUtil.isEmpty(result)) {
            throw new BaseException("您输入的老人信息有误，请重新输入！");
        }
        // 当前用户的id
        Long userId = UserThreadLocal.getUserId();
        // 查询老人是否已经绑定过了
        FamilyMemberElder elder = familyMemberElderService.lambdaQuery()
                .eq(FamilyMemberElder::getFamilyMemberId, userId)
                .eq(FamilyMemberElder::getElderId, result.getElderId())
                .one();
        if (ObjectUtil.isNotEmpty(elder)) {
            throw new BaseException("该老人您已经绑定过了，请勿重复绑定~");
        }
        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        familyMemberElder.setFamilyMemberId(userId);
        familyMemberElder.setElderId(result.getId());
        familyMemberElder.setRemark(remark);
        familyMemberElderService.insertFamilyMemberElder(familyMemberElder);

    }


    @Autowired
    private IFamilyMemberService  familyMemberService;

    @Autowired
    private ElderMapper elderMapper;

    @Override
    public List<FamilyMemberElderVo> my() {
        Long userId = UserThreadLocal.getUserId();
        // 查询当前用户关联的老人 ID 列表
        List<Long> elderIds = familyMemberMapper.selectElderIdsByUserId(userId);

        if (CollectionUtils.isEmpty(elderIds)) {
            return Collections.emptyList(); // 如果没有关联老人，返回空列表
        }

        // 查询老人详细信息
        List<Elder> elderList = elderMapper.selectBatchIds(elderIds);

        // 封装结果
        List<FamilyMemberElderVo> result = new ArrayList<>();
        for (Elder elder : elderList) {
            FamilyMemberElderVo vo = new FamilyMemberElderVo();
            vo.setId(elder.getId());
            vo.setElderId(Math.toIntExact(elder.getId()));
            vo.setElderName(elder.getName());
            result.add(vo);
        }

        return result;
    }


    @Override
    public List<ElderDateVo> getFamilyList() {
        Long familyMemberId =  UserThreadLocal.getUserId();
        List<ElderDateVo> list = familyMemberMapper.selectFamilyMember(familyMemberId);
        return list;
    }

    @Override
    public DeviceDateStatusListVo getDevicePropertyStatus(DevicePropertyDto devicePropertyDto) {
        String HashKey = devicePropertyDto.getProductKey() + "_" + devicePropertyDto.getDeviceName();
        Object o = redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, HashKey);
        if (o == null){
            throw new BaseException("设备数据不存在");
        }
        List<DeviceData> list = JSONUtil.toList(o.toString(), DeviceData.class);
        DeviceDateStatusListVo deviceStatusList = new DeviceDateStatusListVo();
        List<PropertyStatusInfoVo> propertyStatusInfoList = new ArrayList<>();
        list.forEach(deviceData -> {
            PropertyStatusInfoVo propertyStatusInfoVo = new PropertyStatusInfoVo();
            if (deviceData.getDataValue().contains(".")){
                propertyStatusInfoVo.setDataType("double");
            }else {
                propertyStatusInfoVo.setDataType("int");
            }
            String functionId = deviceData.getFunctionId();
            propertyStatusInfoVo.setIdentifier(deviceData.getFunctionId());
            if (Objects.equals(functionId, "BodyTemp")){
                propertyStatusInfoVo.setName("体温");
            }else if(Objects.equals(functionId, "BloodOxygen")){
                propertyStatusInfoVo.setName("血氧");
            }else if (Objects.equals(functionId, "HeartRate")){
                propertyStatusInfoVo.setName("心率");
            }else if (Objects.equals(functionId, "BatteryPercentage")){
                propertyStatusInfoVo.setName("用电量");
            }
            propertyStatusInfoVo.setTime(String.valueOf(deviceData.getAlarmTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
            propertyStatusInfoVo.setUnit("null");
            propertyStatusInfoVo.setValue(deviceData.getDataValue());
            propertyStatusInfoList.add(propertyStatusInfoVo);
        });
        DeviceDateStatusVo deviceStatusVo = new DeviceDateStatusVo();
        deviceStatusVo.setPropertyStatusInfo(propertyStatusInfoList);
        deviceStatusList.setList(deviceStatusVo);
        return deviceStatusList;
    }

    @Override
    public List<DeviceDataListVo> queryDeviceDataListByDay(DeviceDataListDto deviceDataListDto) {
        Long startTime = deviceDataListDto.getStartTime();
        LocalDateTime localStartTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.systemDefault());
        Long endTime = deviceDataListDto.getEndTime();
        LocalDateTime localEndTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(endTime), ZoneId.systemDefault());
        String iotId = deviceDataListDto.getIotId();
        String functionId = deviceDataListDto.getFunctionId();
        List<DeviceDataListVo> list = deviceDataService.queryDeviceDataListByDay(iotId,functionId,localStartTime,localEndTime);
        return list;
    }

    @Override
    public List<DeviceDataListVo> queryDeviceDataListByWeek(DeviceDataListDto deviceDataListDto) {
        Long startTime = deviceDataListDto.getStartTime();
        LocalDateTime localStartTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.systemDefault());
        Long endTime = deviceDataListDto.getEndTime();
        LocalDateTime localEndTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(endTime), ZoneId.systemDefault());
        String iotId = deviceDataListDto.getIotId();
        String functionId = deviceDataListDto.getFunctionId();
        List<DeviceDataListVo> list = deviceDataService.queryDeviceDataListByWeek(iotId,functionId,localStartTime,localEndTime);
        return list;
    }
}
